<template>
	<view class="add-log-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-back" @click="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<text class="nav-title">添加健康记录</text>
			<view class="nav-submit" @click="submitLog">提交</view>
		</view>

		<!-- 记录表单 -->
		<view class="log-form">
			<!-- 记录类型选择 (全宽) -->
			<!-- <view class="form-section form-full-width">
				<view class="section-title">记录类型</view>
				<view class="log-type-list">
					<view class="log-type-item" v-for="(item, index) in logTypes" :key="index"
						:class="{'type-active': selectedType === item.value}" @click="selectLogType(item.value)">
						<text class="iconfont" :class="item.icon"></text>
						<text class="type-name">{{item.name}}</text>
					</view>
				</view>
			</view> -->

			<!-- 左侧区域 -->
			<view class="form-left">
				<!-- 标题输入 -->
				<view class="form-section">
					<view class="section-title">标题</view>
					<view class="input-wrapper">
						<input class="form-input" type="text" v-model="logForm.title" placeholder="请输入记录标题"
							maxlength="20" />
						<text class="input-count">{{logForm.title.length}}/20</text>
					</view>
				</view>

				<!-- 描述内容 -->
				<view class="form-section">
					<view class="section-title">描述</view>
					<view class="textarea-wrapper">
						<textarea class="form-textarea" v-model="logForm.description" placeholder="请详细描述宠物的健康状况..."
							maxlength="200"></textarea>
						<text class="input-count textarea-count">{{logForm.description.length}}/200</text>
					</view>
				</view>

				<!-- 日期时间选择 -->
				<view class="form-section">
					<view class="section-title">记录时间</view>
					<view class="datetime-picker">
						<view class="date-picker" @click="openDatePicker">
							<text class="picker-value">{{logForm.date || '选择日期'}}</text>
							<text class="iconfont icon-calendar"></text>
						</view>
						<view class="time-picker" @click="openTimePicker">
							<text class="picker-value">{{logForm.time || '选择时间'}}</text>
							<text class="iconfont icon-time"></text>
						</view>
					</view>
				</view>
				<!-- 图片上传 -->
				<!-- 	<view class="form-section">
					<view class="section-title">上传图片</view>
					<view class="image-uploader">
						<view class="image-list">
							<view class="image-item" v-for="(item, index) in logForm.images" :key="index">
								<image :src="item" class="preview-image" mode="aspectFill"></image>
								<view class="delete-btn" @click="deleteImage(index)">
									<text class="iconfont icon-delete"></text>
								</view>
							</view>
							<view class="upload-btn" @click="chooseImage" v-if="logForm.images.length < 4">
								<text class="iconfont icon-camera"></text>
								<text class="upload-text">上传图片</text>
							</view>
						</view>
						<text class="upload-tip">最多可上传4张图片</text>
					</view>
				</view> -->
			</view>

			<!-- 右侧区域 -->
			<!-- <view class="form-right"> -->
			<!-- 健康指标记录（根据记录类型显示不同的指标） -->
			<!-- <view class="form-section" v-if="showHealthMetrics">
					<view class="section-title">健康指标</view>
					<view class="metrics-form">
						<view class="metric-item" v-if="selectedType === 'diet'">
							<text class="metric-label">食量(g)</text>
							<view class="metric-input-wrapper">
								<input class="metric-input" type="digit" v-model="logForm.metrics.foodAmount"
									placeholder="0" />
								<text class="metric-unit">g</text>
							</view>
						</view>
						<view class="metric-item" v-if="selectedType === 'diet'">
							<text class="metric-label">饮水量(ml)</text>
							<view class="metric-input-wrapper">
								<input class="metric-input" type="digit" v-model="logForm.metrics.waterAmount"
									placeholder="0" />
								<text class="metric-unit">ml</text>
							</view>
						</view>
						<view class="metric-item" v-if="selectedType === 'weight' || selectedType === 'examination'">
							<text class="metric-label">体重</text>
							<view class="metric-input-wrapper">
								<input class="metric-input" type="digit" v-model="logForm.metrics.weight"
									placeholder="0.0" />
								<text class="metric-unit">kg</text>
							</view>
						</view>
						<view class="metric-item"
							v-if="selectedType === 'temperature' || selectedType === 'examination'">
							<text class="metric-label">体温</text>
							<view class="metric-input-wrapper">
								<input class="metric-input" type="digit" v-model="logForm.metrics.temperature"
									placeholder="0.0" />
								<text class="metric-unit">°C</text>
							</view>
						</view>
						<view class="metric-item" v-if="selectedType === 'activity'">
							<text class="metric-label">运动时长</text>
							<view class="metric-input-wrapper">
								<input class="metric-input" type="digit" v-model="logForm.metrics.activityDuration"
									placeholder="0" />
								<text class="metric-unit">分钟</text>
							</view>
						</view>
					</view>
				</view> -->

			<!-- 提醒设置 -->
			<!-- <view class="form-section">
					<view class="reminder-header">
						<view class="section-title">添加提醒</view>
						<switch @change="toggleReminder" :checked="logForm.reminder.enabled" color="#F9CB43" />
					</view>
					<view class="reminder-form" v-if="logForm.reminder.enabled">
						<view class="reminder-type">
							<view class="reminder-type-item" :class="{'type-active': logForm.reminder.type === 'once'}"
								@click="setReminderType('once')">一次性</view>
							<view class="reminder-type-item" :class="{'type-active': logForm.reminder.type === 'daily'}"
								@click="setReminderType('daily')">每天</view>
							<view class="reminder-type-item"
								:class="{'type-active': logForm.reminder.type === 'weekly'}"
								@click="setReminderType('weekly')">每周</view>
						</view>
						<view class="reminder-time-picker" @click="openReminderTimePicker">
							<text class="reminder-time-label">提醒时间</text>
							<view class="reminder-time-value">
								<text>{{logForm.reminder.time || '请选择时间'}}</text>
								<text class="iconfont icon-right"></text>
							</view>
						</view>
						<view class="reminder-note">
							<text class="reminder-note-label">提醒内容</text>
							<input class="reminder-note-input" type="text" v-model="logForm.reminder.note"
								placeholder="请输入提醒内容" />
						</view>
					</view>
				</view> -->
			<!-- </view> -->
		</view>

		<!-- 提交按钮 -->
		<view class="submit-button-area">
			<view class="submit-button" @click="submitLog">
				<text>保存记录</text>
			</view>
		</view>

		<!-- 底部安全区域 -->
		<view class="safe-bottom"></view>
	</view>
</template>

<script>
	import {
		userApi
	} from '../../../api/user';

	export default {
		data() {
			return {
				petId: '',
				petInfo: {
					id: '123456',
					name: '小毛球',
					avatar: '/static/pet-test.png'
				},
				logTypes: [{
						name: '饮食',
						value: 'diet',
						icon: 'icon-diet'
					},
					{
						name: '体重',
						value: 'weight',
						icon: 'icon-weight'
					},
					{
						name: '体温',
						value: 'temperature',
						icon: 'icon-temperature'
					},
					{
						name: '运动',
						value: 'activity',
						icon: 'icon-activity'
					},
					{
						name: '服药',
						value: 'medicine',
						icon: 'icon-medicine'
					},
					{
						name: '体检',
						value: 'examination',
						icon: 'icon-examination'
					},
					{
						name: '症状',
						value: 'symptom',
						icon: 'icon-symptom'
					},
					{
						name: '其他',
						value: 'other',
						icon: 'icon-other'
					}
				],
				selectedType: 'diet',
				showHealthMetrics: true,
				logForm: {
					title: '',
					description: '',
					date: this.formatDate(new Date()),
					time: this.formatTime(new Date()),
					images: [],
					metrics: {
						weight: '',
						temperature: '',
						foodAmount: '',
						waterAmount: '',
						activityDuration: ''
					},
					reminder: {
						enabled: false,
						type: 'once',
						time: '',
						note: ''
					}
				}
			}
		},
		mounted() {

		},
		methods: {
			// 格式化日期为 YYYY-MM-DD
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 格式化时间为 HH:MM
			formatTime(date) {
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				return `${hours}:${minutes}`;
			},

			// 获取宠物基本信息
			getPetInfo() {
				// 实际应用中，这里会调用API获取宠物信息
				// uni.request({
				//   url: 'api/pet/info',
				//   method: 'GET',
				//   data: { petId: this.petId },
				//   success: (res) => {
				//     this.petInfo = res.data;
				//   }
				// });

				// 使用静态数据模拟
				console.log('获取宠物信息，ID:', this.petId);
			},

			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 选择记录类型
			selectLogType(type) {
				this.selectedType = type;

				// 根据类型决定是否显示健康指标
				const metricsTypes = ['diet', 'weight', 'temperature', 'activity', 'examination'];
				this.showHealthMetrics = metricsTypes.includes(type);

				// 清空之前的指标数据
				this.logForm.metrics = {
					weight: '',
					temperature: '',
					foodAmount: '',
					waterAmount: '',
					activityDuration: ''
				};

				// 根据类型设置默认标题
				const titleMap = {
					diet: '日常饮食',
					weight: '体重记录',
					temperature: '体温记录',
					activity: '运动记录',
					medicine: '服药记录',
					examination: '体检记录',
					symptom: '症状记录',
					other: '其他记录'
				};

				this.logForm.title = titleMap[type] || '';
			},

			// 打开日期选择器
			openDatePicker() {
				uni.showDatePicker({
					current: this.logForm.date,
					success: (res) => {
						this.logForm.date = res.date;
					}
				});
			},

			// 打开时间选择器
			openTimePicker() {
				uni.showTimeSelector({
					current: this.logForm.time,
					success: (res) => {
						this.logForm.time = res.time;
					}
				});
			},

			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 4 - this.logForm.images.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 合并新选择的图片
						this.logForm.images = [...this.logForm.images, ...res.tempFilePaths];
					}
				});
			},

			// 删除已选择的图片
			deleteImage(index) {
				this.logForm.images.splice(index, 1);
			},

			// 切换提醒开关
			toggleReminder(e) {
				this.logForm.reminder.enabled = e.detail.value;

				// 如果开启提醒，设置默认时间
				if (this.logForm.reminder.enabled && !this.logForm.reminder.time) {
					const now = new Date();
					this.logForm.reminder.time = this.formatTime(now);
				}
			},

			// 设置提醒类型
			setReminderType(type) {
				this.logForm.reminder.type = type;
			},

			// 打开提醒时间选择器
			openReminderTimePicker() {
				uni.showTimeSelector({
					current: this.logForm.reminder.time || this.formatTime(new Date()),
					success: (res) => {
						this.logForm.reminder.time = res.time;
					}
				});
			},

			// 验证表单
			validateForm() {
				if (!this.logForm.title.trim()) {
					uni.showToast({
						title: '请输入记录标题',
						icon: 'none'
					});
					return false;
				}

				if (!this.logForm.description.trim()) {
					uni.showToast({
						title: '请输入记录描述',
						icon: 'none'
					});
					return false;
				}

				if (!this.logForm.date) {
					uni.showToast({
						title: '请选择记录日期',
						icon: 'none'
					});
					return false;
				}

				if (!this.logForm.time) {
					uni.showToast({
						title: '请选择记录时间',
						icon: 'none'
					});
					return false;
				}

				// 验证提醒相关信息
				if (this.logForm.reminder.enabled) {
					if (!this.logForm.reminder.time) {
						uni.showToast({
							title: '请选择提醒时间',
							icon: 'none'
						});
						return false;
					}

					if (!this.logForm.reminder.note.trim()) {
						uni.showToast({
							title: '请输入提醒内容',
							icon: 'none'
						});
						return false;
					}
				}

				return true;
			},

			// 提交记录
			async submitLog() {
				try {
					if (!this.validateForm()) {
						return;
					}

					// 构建提交的数据
					const logData = {
						userId: uni.getStorageSync('userId'),
						type: this.selectedType,
						title: this.logForm.title,
						content: this.logForm.description,
						createTime: `${this.logForm.date} ${this.logForm.time}:00`,
						metrics: this.showHealthMetrics ? this.logForm.metrics : null,
						reminder: this.logForm.reminder.enabled ? this.logForm.reminder : null
					};

					const result = userApi.addHealthRecords(logData)

					// 显示加载提示
					uni.showLoading({
						title: '保存中...'
					});
					uni.navigateTo({
						url: '/pages/health/healthFiles'
					})
					console.log('提交成功:', result);
				} catch (error) {
					console.error('提交失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '提交失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
				}

				// 实际应用中的代码示例:
				/*
				// 1. 先上传图片
				const uploadPromises = this.logForm.images.map(imgPath => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: 'api/upload',
							filePath: imgPath,
							name: 'file',
							success: (res) => {
								const data = JSON.parse(res.data);
								resolve(data.url);
							},
							fail: (err) => {
								reject(err);
							}
						});
					});
				});
				
				Promise.all(uploadPromises).then(imageUrls => {
					// 2. 图片上传完成后，提交表单数据
					logData.images = imageUrls;
					
					uni.request({
						url: 'api/pet/health-log',
						method: 'POST',
						data: logData,
						success: (res) => {
							uni.hideLoading();
							if (res.data.success) {
								uni.showToast({
									title: '保存成功',
									icon: 'success',
									success: () => {
										// 延迟返回上一页
										setTimeout(() => {
											uni.navigateBack();
										}, 1500);
									}
								});
							} else {
								uni.showToast({
									title: res.data.message || '保存失败',
									icon: 'none'
								});
							}
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						}
					});
				}).catch(() => {
					uni.hideLoading();
					uni.showToast({
						title: '图片上传失败',
						icon: 'none'
					});
				});
				*/
			}
		}
	}
</script>

<style scoped>
	.add-log-container {
		/* background-color: #f5f5f5; */
		min-height: 100vh;
		max-width: 1200px;
		margin: 0 auto;
		display: flex;
		flex-direction: column;
	}

	/* 导航栏样式 */
	.nav-bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		height: 70px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 50px;
		z-index: 10;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.nav-back {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		cursor: pointer;
	}

	.nav-title {
		font-size: 20px;
		font-weight: bold;
	}

	.nav-submit {
		font-size: 16px;
		color: #F9CB43;
		cursor: pointer;
	}

	/* 表单区域样式 - 改为左右两栏布局 */
	.log-form {
		padding: 20px;
		margin-top: 90px;
		display: flex;
		flex-wrap: wrap;
		gap: 20px;
	}

	.form-section {
		background-color: #fff;
		border-radius: 8px;
		padding: 20px;
		margin-bottom: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
	}

	/* 左侧区域 - 基本信息 */
	.form-left {
		flex: 1;
		min-width: 300px;
	}

	/* 右侧区域 - 详细信息 */
	.form-right {
		flex: 1;
		min-width: 300px;
	}

	/* 记录类型选择区域占满宽度 */
	.form-full-width {
		width: 100%;
	}

	.section-title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
		padding-bottom: 10px;
		border-bottom: 1px solid #eee;
	}

	/* 记录类型选择 */
	.log-type-list {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
	}

	.log-type-item {
		width: calc(25% - 10px);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
		transition: all 0.3s;
		border-radius: 8px;
		cursor: pointer;
	}

	.log-type-item .iconfont {
		font-size: 24px;
		color: #999;
		margin-bottom: 10px;
	}

	.type-name {
		font-size: 14px;
		color: #666;
	}

	.type-active {
		background-color: rgba(249, 203, 67, 0.1);
		border-radius: 8px;
	}

	.type-active .iconfont {
		color: #F9CB43;
	}

	.type-active .type-name {
		color: #F9CB43;
	}

	/* 输入框样式 */
	.input-wrapper {
		position: relative;
		border: 1px solid #eee;
		border-radius: 8px;
		overflow: hidden;
		height: 50px;
		margin-bottom: 20px;
	}

	.form-input {
		height: 50px;
		padding: 0 15px;
		font-size: 16px;
		width: 100%;
		border: none;
		outline: none;
	}

	.input-count {
		position: absolute;
		right: 15px;
		bottom: 8px;
		font-size: 14px;
		color: #999;
	}

	/* 文本域样式 */
	.textarea-wrapper {
		position: relative;
		border: 1px solid #eee;
		border-radius: 8px;
		overflow: hidden;
		padding: 15px;
		margin-bottom: 20px;
	}

	.form-textarea {
		width: 100%;
		height: 150px;
		font-size: 16px;
		border: none;
		outline: none;
		resize: none;
	}

	.textarea-count {
		position: absolute;
		right: 15px;
		bottom: 15px;
		font-size: 14px;
		color: #999;
	}

	/* 日期时间选择器 */
	.datetime-picker {
		display: flex;
		gap: 15px;
		margin-bottom: 20px;
	}

	.date-picker,
	.time-picker {
		flex: 1;
		background-color: #f9f9f9;
		height: 50px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 15px;
		border-radius: 8px;
		cursor: pointer;
	}

	.picker-value {
		font-size: 16px;
		color: #333;
	}

	/* 图片上传 */
	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 15px;
	}

	.image-item,
	.upload-btn {
		width: 120px;
		height: 120px;
		border-radius: 8px;
		overflow: hidden;
		position: relative;
	}

	.preview-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 30px;
		height: 30px;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 0 0 0 8px;
		cursor: pointer;
	}

	.delete-btn .iconfont {
		font-size: 16px;
		color: #fff;
	}

	.upload-btn {
		background-color: #f9f9f9;
		border: 1px dashed #ddd;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.upload-btn .iconfont {
		font-size: 24px;
		color: #999;
		margin-bottom: 10px;
	}

	.upload-text {
		font-size: 14px;
		color: #999;
	}

	.upload-tip {
		font-size: 13px;
		color: #999;
		margin-top: 10px;
	}

	/* 健康指标 */
	.metrics-form {
		display: flex;
		flex-wrap: wrap;
		gap: 15px;
	}

	.metric-item {
		width: calc(50% - 8px);
		box-sizing: border-box;
	}

	.metric-label {
		font-size: 15px;
		color: #666;
		margin-bottom: 8px;
		display: block;
	}

	.metric-input-wrapper {
		display: flex;
		align-items: center;
		height: 45px;
		background-color: #f9f9f9;
		border-radius: 8px;
		padding: 0 15px;
	}

	.metric-input {
		flex: 1;
		height: 45px;
		font-size: 15px;
		border: none;
		outline: none;
		background: transparent;
	}

	.metric-unit {
		font-size: 15px;
		color: #999;
		margin-left: 10px;
	}

	/* 提醒设置 */
	.reminder-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15px;
	}

	.reminder-type {
		display: flex;
		gap: 10px;
		margin-bottom: 15px;
	}

	.reminder-type-item {
		flex: 1;
		height: 45px;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f9f9f9;
		border-radius: 8px;
		font-size: 15px;
		color: #666;
		cursor: pointer;
	}

	.reminder-time-picker {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 50px;
		padding: 0 15px;
		background-color: #f9f9f9;
		border-radius: 8px;
		margin-bottom: 15px;
		cursor: pointer;
	}

	.reminder-time-label {
		font-size: 15px;
		color: #666;
	}

	.reminder-time-value {
		display: flex;
		align-items: center;
		font-size: 15px;
		color: #333;
	}

	.reminder-time-value .iconfont {
		margin-left: 10px;
		font-size: 14px;
		color: #999;
	}

	.reminder-note {
		display: flex;
		align-items: center;
		height: 50px;
		padding: 0 15px;
		background-color: #f9f9f9;
		border-radius: 8px;
	}

	.reminder-note-label {
		width: 100px;
		font-size: 15px;
		color: #666;
	}

	.reminder-note-input {
		flex: 1;
		height: 50px;
		font-size: 15px;
		border: none;
		outline: none;
		background: transparent;
	}

	/* 提交按钮 */
	.submit-button-area {
		padding: 20px 30px 40px;
		width: 400rpx;
		margin: 0 auto;
	}

	.submit-button {
		height: 50px;
		background-color: #F9CB43;
		border-radius: 25px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 18px;
		font-weight: bold;
		box-shadow: 0 4px 12px rgba(249, 203, 67, 0.3);
		cursor: pointer;
		transition: all 0.3s;
	}

	.submit-button:hover {
		background-color: #f0c235;
		transform: translateY(-2px);
	}

	.safe-bottom {
		height: 30px;
	}

	/* 图标字体 */
	.iconfont {
		font-family: "iconfont";
		font-size: 20px;
		color: #F9CB43;
	}

	/* 响应式布局 */
	@media screen and (max-width: 768px) {
		.log-form {
			flex-direction: column;
		}

		.form-left,
		.form-right {
			width: 100%;
		}

		.metric-item {
			width: 100%;
		}

		.log-type-item {
			width: calc(33.33% - 10px);
		}
	}
</style>